<script setup lang="ts">
  import { ref, watch, reactive, computed } from 'vue';
  import {
    Tabs,
    TabPane,
    Card,
    Row,
    Col,
    Avatar,
    Image,
    Popover,
    Divider,
    List,
    ListItem,
    Message,
  } from '@arco-design/web-vue';
  import { IconShareAlt } from '@arco-design/web-vue/es/icon';
  import { useGlobalScroll } from '/@/hooks/useScroll';
  import TalkContainer from '/@/components/TalkContainer.vue';
  import { parseArrayValue } from '/@/utils/helper';
  import { useUserStore } from '/@/store/modules/user';
  import { queryPinCommentsList } from '/@/api/app/pin';
  import { addComment, postCommentStar, postPinStar } from '/@/api/web/pin';
  import type { CommentRecord } from '/@/api/app/model/pinModel';
  import type { HostpotPage } from '/@/api/model/pinsModel';
  import likeSvg from '/@/assets/pins/like.svg';
  import shareIcon from '/@/assets/pins/share.svg';
  import commentIcon from '/@/assets/pins/comment.svg';
  import DOMPurify from 'dompurify';
  import { queryHostPageList } from '/@/api/pins';
  import { CommentAction, CommentList } from '/@/components/Comment';
  import { useRouter, useRoute } from 'vue-router';

  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();
  const { arrivedState } = useGlobalScroll({ offset: { bottom: 100 } });
  const pinsListLoading = ref(false);
  const getCommunityId = computed(() => {
    return route.params.id as string;
  });

  const onContentClick = (ev: Event) => {
    const target = ev.target as Element;
    if (target.nodeName === 'SPAN' && target.getAttribute('data-node') === 'theme') {
      window.open(`/pins/topic/${target.getAttribute('id')}`, '_blank');
    }
  };

  watch(
    () => arrivedState.bottom,
    (isReachBottom) => {
      if (isReachBottom) {
        if (pinsListLoading.value) return;
        pinsParams.page++;
      }
    },
  );
  const pinsParams = reactive({
    page: 1,
    topic_id: '',
  });
  type PinRecord = {
    raw: HostpotPage;
    content: string;
    img: string[];
    commentOpened: boolean;
    actionOpened: boolean;
    commentList?: Partial<CommentRecord>[];
    comment: string;
  };
  const pinsList = ref<PinRecord[]>([]);
  const orderRef = ref<number>(0);

  const reloadCommentList = async (item: PinRecord) => {
    const data = await queryPinCommentsList({ hotspot_id: item.raw.id, ord: orderRef.value });
    // item.commentList = data.map((raw) => {
    //   return {
    //     raw,
    //     stared: raw.stared,
    //     isCommenting: false,
    //   };
    // });
    item.commentList = data;
  };

  const onOrderChange = (item: PinRecord, value: number) => {
    orderRef.value = value;
    reloadCommentList(item);
  };

  const onSwitchComment = async (item: PinRecord) => {
    if (item.commentOpened) {
      item.commentOpened = false;
    } else {
      item.commentOpened = true;
      await reloadCommentList(item);
    }
  };

  const onComment = async (item: PinRecord, comment?: string, file?: string) => {
    if (!userStore.userInfo) {
      Message.error('请先登录');
      return;
    }
    if (!comment) {
      return;
    }

    try {
      await addComment({
        content: comment,
        hotspot_id: item.raw.id,
        image: file,
        to_user_id: item.raw.user_id,
      });
      Message.success('评论成功');
      await reloadCommentList(item);
    } catch (error) {
      Message.error((error as Error).message || '评论失败');
    }
  };

  const onViewUser = (item: CommentRecord) => {
    // window.open(`/user/${item.user_id}`, '_blank');
    router.push(`/user/${item.user_id}`);
  };

  const onViewToUser = (item: CommentRecord) => {
    // window.open(`/user/${item.to_user_id}`, '_blank');
    router.push(`/user/${item.user_id}`);
  };

  const onListComment = async (
    item: PinRecord,
    commentItem: Partial<CommentRecord>,
    comment?: string,
    file?: string,
    topComment?: Partial<CommentRecord>,
  ) => {
    if (!comment) {
      return;
    }

    try {
      await addComment({
        content: comment,
        hotspot_id: item.raw.id,
        to_comment_id: commentItem.id,
        image: file,
        top_id: topComment ? topComment.id : commentItem.id,
        ...(topComment && {
          to_user_id: commentItem.user_id,
        }),
      });
      Message.success('评论成功');
      await reloadCommentList(item);
    } catch (error) {
      Message.error((error as Error).message || '评论失败');
    }
  };

  const onListStar = async (
    item: PinRecord,
    commentItem: Partial<CommentRecord>,
    cancel: boolean,
  ) => {
    const data = await postCommentStar({
      comment_id: commentItem.id as number,
    });
    commentItem.star = data.star;
    commentItem.stared = !cancel;
  };

  const onViewAllComments = (data: PinRecord) => {
    window.open(`/pins/pin/${data.raw.id}`, '_blank');
  };

  const onPinLike = async (data: PinRecord) => {
    await postPinStar({
      hotspot_id: data.raw.id as number,
    });
  };

  watch(
    [pinsParams, getCommunityId],
    async () => {
      try {
        if (pinsListLoading.value) return;
        pinsListLoading.value = true;
        let res = await queryHostPageList({
          ...pinsParams,
          community_id: getCommunityId.value,
          size: 20,
        });
        res.list.forEach((item) => {
          pinsList.value.push({
            raw: item,
            content: DOMPurify.sanitize(item.content),
            img: parseArrayValue(item.img),
            commentOpened: false,
            actionOpened: true,
            // commentList: null,
            comment: '',
          });
        });
        pinsListLoading.value = false;
      } catch (error) {}
    },
    { immediate: true },
  );
</script>

<template>
  <div class="p-pin-index w-full">
    <Card class="type-card mb-[10px] rounded-[8px] bg-[rgba(255,255,255,0.8)]" :bordered="false">
      <tabs default-active-key="1" class="type-tabs">
        <tab-pane key="1">
          <template #title>
            <span class="font-bold">热门</span>
          </template>
        </tab-pane>
        <tab-pane key="2">
          <template #title>
            <span class="font-bold">最新</span>
          </template>
        </tab-pane>
      </tabs>
    </Card>
    <List :bordered="false" :loading="pinsListLoading">
      <ListItem v-for="item of pinsList" :key="item.raw.id" class="p-0">
        <Card
          class="user-topic-card mb-[10px] rounded-[8px] bg-[rgba(255,255,255,0.8)]"
          :bordered="false"
        >
          <Row>
            <Col :span="1" class="mt-[2px]">
              <Avatar :size="45" :image-url="item.raw.user_icon" />
            </Col>
            <Col :span="12" class="ml-[20px]">
              <div class="text-[18px] font-bold">{{ item.raw.user_name }}</div>
              <div>
                <span class="text-[12px] text-[#909090]">{{ $timeAgo(item.raw.createTime) }}</span>
              </div>
            </Col>
            <Col :span="9" class="text-right" v-if="item.raw.star">
              <Avatar
                v-for="i of 4"
                :key="i"
                :style="{ 'z-index': i }"
                class="filter-shadow ml-[-8px] bg-transparent"
                :size="20"
                :image-url="item.raw.user_icon"
              />
              <span class="font-[400] text-[rgba(0,0,0,0.5)] ml-4">等人赞过</span>
            </Col>
          </Row>
          <Row class="overflow-auto mb-2 pt-[20px]">
            <Col :span="1" />
            <Col
              :span="23"
              class="text-[16px] ml-[55px] py-[10px] box-border rounded-[8px] relative"
            >
              <!-- <img :src="triangleImg" class="absolute w-[34px] left-[17px] top-[-18px]" /> -->
              <TalkContainer>
                <div
                  v-html="item.content"
                  class="content w-full text-[rgba(0,0,0,0.8) font-[500] text-[14px]"
                  @click="onContentClick"
                ></div>
              </TalkContainer>
              <div v-if="item.img?.length < 5" class="w-full max-h-[350px] overflow-hidden">
                <Image
                  v-for="(img, i) of item?.img"
                  :key="i"
                  class="w-[200px] h-[200px] rounded-[4px] pt-[6px] pr-[6px] box-border"
                  :src="img"
                />
              </div>
              <div v-else class="w-full max-h-[350px] overflow-hidden">
                <Image
                  v-for="(img, index) of item?.img"
                  :key="index"
                  class="w-[110px] h-[110px] pt-[6px] pr-[6px] box-border"
                  :src="img"
                />
              </div>
            </Col>
          </Row>
          <Divider />
          <Row class="cursor-pointer flex justify-end">
            <Col
              :span="2"
              class="text-center flex items-center justify-center text-[rgba(0,0,0,0.5)]"
              @click="onPinLike(item)"
            >
              <img :src="likeSvg" class="w-[16px] h-[16px] mr-[4px]" />
              点赞
            </Col>
            <Col
              :span="2"
              class="text-center flex items-center justify-center text-[rgba(0,0,0,0.5)]"
              @click="onSwitchComment(item)"
            >
              <img :src="commentIcon" class="w-[16px] h-[16px] mr-[4px]" />
              评论
            </Col>
            <Popover title="" trigger="click" position="bottom" content-class="emoji-content">
              <template #content>
                <div class="w-132px">
                  <Row>
                    <Col class="flex items-center"> <IconShareAlt class="mr-2" /> 复制链接1</Col>
                  </Row>
                  <Divider />
                  <Row>
                    <Col class="flex items-center"> <IconShareAlt class="mr-2" /> 复制链接2</Col>
                  </Row>
                  <Divider />
                  <Row>
                    <Col class="flex items-center"> <IconShareAlt class="mr-2" /> 复制链接3</Col>
                  </Row>
                </div>
              </template>
              <Col
                :span="2"
                class="text-center flex items-center justify-center text-[rgba(0,0,0,0.5)]"
              >
                <img :src="shareIcon" class="w-[16px] h-[16px] mr-[4px]" />
                转发
              </Col>
            </Popover>
          </Row>

          <div v-if="item.commentOpened" class="max-w-[660px] mx-auto">
            <div class="flex py-[24px] justify-center items-start">
              <Avatar class="flex-none mr-[16px]" :imageUrl="userStore.userInfo?.icon" />
              <div class="flex-grow flex-shrink">
                <CommentAction
                  @comment="(...args) => onComment(item, ...args)"
                  :auto-focus="false"
                />
              </div>
            </div>
            <CommentList
              :order="orderRef"
              @change-order="(...args) => onOrderChange(item, ...args)"
              @view-all="onViewAllComments(item)"
              :limit="2"
              @view-user="onViewUser"
              @view-to-user="onViewToUser"
              @comment="(...args) => onListComment(item, ...args)"
              @star="(...args) => onListStar(item, ...args)"
              :data="item.commentList"
            />
          </div>
        </Card>
      </ListItem>
    </List>
  </div>
</template>

<style scoped>
  .content :deep([data-node='theme']) {
    cursor: pointer;
  }

  .type-card :deep(.arco-tabs-content) {
    padding: 0 !important;
  }

  .type-card :deep(.arco-tabs-nav::before) {
    display: none !important;
  }

  .filter-shadow {
    filter: drop-shadow(-2px 0px 4px rgba(0, 0, 0, 0.25));
  }

  .tools-left .tools-left-item:hover {
    color: #1e80ff !important;
  }
</style>
